import { UploadOutlined } from '@ant-design/icons'
import { Button, Form, message, Upload } from 'antd'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import React, { useState, forwardRef, useImperativeHandle, ForwardRefRenderFunction, useEffect } from 'react'

const UploadPdf: ForwardRefRenderFunction<{ fileList: UploadFile[] }, any> = (_: any, ref) => {
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const CanChange = (file: RcFile | UploadFile, fileList: Array<UploadFile>): boolean => {
    const { type } = file
    const isJpgOrPng = type === 'application/pdf' || type === 'application/epub+zip'
    if (!isJpgOrPng) {
      message.error('你只能上传 pdf/epub 文件!')
      return false
    }
    if (fileList.length >= 5) {
      message.error('最多上传5个文件!')
      return false
    }
    return true
  }
  const beforeUpload = (file: RcFile) => {
    return false
  }
  const handleChange: UploadProps['onChange'] = ({ file, fileList }) => {
    const result = CanChange(file, fileList)
    result && setFileList(fileList)
  }
  useImperativeHandle(ref, () => {
    return {
      fileList,
      setFileList
    }
  })
  const onRemove = (file: UploadFile) => {
    const index = fileList.indexOf(file)
    const newVideoFileList = fileList.slice()
    newVideoFileList.splice(index, 1)
    setFileList(newVideoFileList)
  }
  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e?.fileList
  }
  return (
    <Form.Item
      name="fileList"
      getValueFromEvent={normFile}
      label="文件上传"
      rules={[{ required: true, message: '请选择你要上传的文件!', type: 'array' }]}
    >
      <Upload
        name="avatar"
        beforeUpload={beforeUpload}
        multiple={true}
        onChange={handleChange}
        maxCount={5}
        fileList={fileList}
        onRemove={file => onRemove(file)}
      >
        <Button icon={<UploadOutlined />}>点击上传(最多上传5个文件)</Button>
      </Upload>
    </Form.Item>
  )
}

export default forwardRef(UploadPdf)
